/*******************************************************************************
 * Copyright (c) 2014-6-26 @author <a href="mailto:iffiff1@hotmail.com">Tyler Chen</a>.
 * All rights reserved.
 *
 * Contributors:
 *     <a href="mailto:iffiff1@hotmail.com">Tyler Chen</a> - initial API and implementation
 ******************************************************************************/
package com.foreveross.project.projectonline.jfinal.plugin;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.iff.infra.util.FCS;
import org.iff.infra.util.Logger;

import com.google.common.collect.Maps;
import com.jfinal.kit.PathKit;
import com.jfinal.kit.StrKit;

/**
 * <pre>
 * Usage:
 * 1. Setting default properties file: ResourceKit.setDefaultProperties(fileName);
 *    @see com.foreveross.cloudsource.config.AppConfig.configConstant(Constants)
 * 2. Get value from System.properties[priority] and default properties file:
 *    ResourceKit.getValue("http.access.enable")
 * 3. Get value from System.properties[priority] and specify properties file:
 *    ResourceKit.getValue("sql.properties", "jdbcUrl")
 * </pre>
 * @author <a href="mailto:iffiff1@hotmail.com">Tyler Chen</a> 
 * @since 2014-6-26
 */
public class ResourceKit {

	protected static final Map<String, Properties> PROP_CACHE = new HashMap<String, Properties>();
	protected static final Map<String, Long> FILE_UPDATE = new HashMap<String, Long>();
	protected static String DEFAUL_PROPS_FILE = null;

	public static void setDefaultProperties(String defaultPropFile) {
		DEFAUL_PROPS_FILE = defaultPropFile;
	}

	public static Properties loadPropertyFile(String fileName) {
		if (StrKit.isBlank(fileName)) {
			Logger.error(FCS.get("[FileNameIsEmpty:{0}]", fileName));
			return null;
		}
		if (fileName.contains("..")) {
			Logger.error(FCS.get("[FileName can not contains \"..\":{0}]",
					fileName));
			return null;
		}

		InputStream inputStream = null;
		String fullFile; // String fullFile = PathUtil.getWebRootPath() + file;
		if (fileName.startsWith(File.separator)) {
			fullFile = PathKit.getWebRootPath() + File.separator + "WEB-INF"
					+ fileName;
		} else {
			fullFile = PathKit.getWebRootPath() + File.separator + "WEB-INF"
					+ File.separator + fileName;
		}
		Properties p = new Properties();
		File file = new File(fullFile);
		if (file == null) {
			return null;
		}
		{//check file update
			Long lastModified = FILE_UPDATE.get(fullFile);
			Properties props = PROP_CACHE.get(fullFile);
			if (lastModified != null
					&& file.lastModified() == lastModified.longValue()
					&& props != null) {
				return props;
			}
		}
		try {
			inputStream = new FileInputStream(file);
			p.load(inputStream);
			{
				FILE_UPDATE.put(fullFile, file.lastModified());
				PROP_CACHE.put(fullFile, p);
			}
		} catch (Exception e) {
			Logger.error(FCS.get("[Properties file can not be loading:{0}]",
					fullFile), e);
		} finally {
			try {
				if (inputStream != null) {
					inputStream.close();
				}
			} catch (Exception e) {
			}
		}
		if (p == null) {
			Logger.error(FCS.get("[Properties file can not be failed:{0}]",
					fullFile));
		}
		return p;
	}
	
	public static String getFixedWebRootPath() {
		String webRootPath = PathKit.getWebRootPath();
		if (new File(webRootPath + File.separator
				+ "src/main/webapp/WEB-INF/web.xml").exists()) {
			return webRootPath + File.separator + "src/main/webapp";
		}
		return webRootPath;
	}

	public static Map<String, String> loadPropertyFileToMap(String file) {
		Properties p = loadPropertyFile(file);
		return Maps.fromProperties(p);
	}

	public static String getValue(String key) {
		return getValue(DEFAUL_PROPS_FILE, key);
	}

	public static String getValue(String fileName, String key) {
		fileName = fileName == null ? DEFAUL_PROPS_FILE : fileName;
		return System.getProperty(key, fileName == null ? null
				: loadPropertyFile(fileName).getProperty(key));
	}
}
